package com.tree.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tree.backend.entity.dto.UserDTO;
import com.tree.backend.entity.dto.UserQueryDTO;
import com.tree.backend.entity.pojo.Enterprise;
import com.tree.backend.entity.pojo.User;
import com.tree.backend.entity.vo.LoginVO;
import com.tree.backend.entity.vo.UserInfoVO;
import com.tree.backend.entity.vo.UserListVO;
import com.tree.backend.entity.vo.UserStatsVO;
import com.tree.backend.exception.GlobalException;
import com.tree.backend.mapper.EnterpriseMapper;
import com.tree.backend.mapper.UserMapper;
import com.tree.backend.service.IUserService;
import com.tree.backend.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户服务实现类
 * </p>
 *
 * @author tree
 * @since 2025-11-04
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final JwtUtil jwtUtil;

    private final EnterpriseMapper enterpriseMapper;

    @Override
    public LoginVO login(String username, String password) {
        // 查找用户
        User user = getOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username));

        // 验证用户是否存在且密码正确
        if (user == null || !password.equals(user.getPassword())) {
            throw new GlobalException(401, "用户名或密码错误");
        }

        // 生成JWT token，包含用户ID和用户类型
        String token = jwtUtil.generateToken(username, user.getId(), user.getUserType());

        // 构建登录响应，包含用户ID、用户类型和企业ID
        return LoginVO.builder()
                .token(token)
                .username(username)
                .userType(user.getUserType())
                .id(user.getId())
                .enterpriseId(user.getEnterpriseId())
                .build();
    }

    @Override
    public UserInfoVO getUserInfo(String username) {
        // 查找用户
        User user = getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));

        if (user == null) {
            throw new GlobalException(404, "用户不存在");
        }

        // 构建用户信息响应
        UserInfoVO userInfoVO = new UserInfoVO();
        BeanUtils.copyProperties(user, userInfoVO);
        return userInfoVO;
    }

    @Override
    public void logout() {
        // JWT是无状态的，服务端不需要特殊处理
        // 客户端只需要删除token即可
        // 这里可以扩展其他业务逻辑，比如记录登出日志等
    }

    @Override
    public UserStatsVO getUserStats() {
        UserStatsVO statsVO = new UserStatsVO();

        // 获取总用户数
        long totalCount = count();
        statsVO.setTotalUserCount((int) totalCount);

        // 获取普通用户数
        long normalUserCount = count(new LambdaQueryWrapper<User>().eq(User::getUserType, 1));
        statsVO.setNormalUserCount((int) normalUserCount);

        // 获取企业用户数
        long enterpriseUserCount = count(new LambdaQueryWrapper<User>().eq(User::getUserType, 2));
        statsVO.setEnterpriseUserCount((int) enterpriseUserCount);

        // 获取管理员用户数
        long adminUserCount = count(new LambdaQueryWrapper<User>().eq(User::getUserType, 3));
        statsVO.setAdminUserCount((int) adminUserCount);

        // 获取激活用户数
        long activeUserCount = count(new LambdaQueryWrapper<User>().eq(User::getStatus, 1));
        statsVO.setActiveUserCount((int) activeUserCount);

        // 获取未激活用户数
        long inactiveUserCount = count(new LambdaQueryWrapper<User>().eq(User::getStatus, 0));
        statsVO.setInactiveUserCount((int) inactiveUserCount);

        return statsVO;
    }

    @Override
    public Page<UserListVO> getUserList(UserQueryDTO queryDTO) {
        // 创建分页对象
        Page<User> page = new Page<>(queryDTO.getPage(), queryDTO.getPageSize());

        // 构建查询条件
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        if (queryDTO.getEnterpriseId() != null) {
            wrapper.eq(User::getEnterpriseId, queryDTO.getEnterpriseId());
        }

        if (queryDTO.getUsername() != null && !queryDTO.getUsername().isEmpty()) {
            wrapper.like(User::getUsername, queryDTO.getUsername());
        }

        if (queryDTO.getUserType() != null) {
            wrapper.eq(User::getUserType, queryDTO.getUserType());
        }

        if (queryDTO.getStatus() != null) {
            wrapper.eq(User::getStatus, queryDTO.getStatus());
        }

        // 执行分页查询
        Page<User> userPage = page(page, wrapper);

        // 转换为VO对象
        Page<UserListVO> resultPage = new Page<>(userPage.getCurrent(), userPage.getSize(), userPage.getTotal());
        List<UserListVO> userListVOs = userPage.getRecords().stream().map(user -> {
            UserListVO userListVO = new UserListVO();
            BeanUtils.copyProperties(user, userListVO);
            Enterprise enterpriseServiceById = enterpriseMapper.selectById(user.getEnterpriseId());
            if (enterpriseServiceById != null) userListVO.setEnterpriseName(enterpriseServiceById.getName());
            return userListVO;
        }).collect(Collectors.toList());

        resultPage.setRecords(userListVOs);
        return resultPage;
    }

    @Override
    public boolean addUser(UserDTO userDTO) {
        // 检查用户名是否已存在
        User existingUser = getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, userDTO.getUsername()));
        if (existingUser != null) {
            throw new GlobalException(400, "用户名已存在");
        }

        // 创建用户对象
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        // 保存用户
        return save(user);
    }

    @Override
    public boolean updateUser(Long userId, UserDTO userDTO) {
        // 检查用户是否存在
        User existingUser = getById(userId);
        if (existingUser == null) {
            throw new GlobalException(404, "用户不存在");
        }

        // 检查用户名是否被其他用户使用
        if (userDTO.getUsername() != null && !userDTO.getUsername().equals(existingUser.getUsername())) {
            User userWithSameUsername = getOne(new LambdaQueryWrapper<User>()
                    .eq(User::getUsername, userDTO.getUsername())
                    .ne(User::getId, userId));
            if (userWithSameUsername != null) {
                throw new GlobalException(400, "用户名已存在");
            }
        }

        // 更新用户信息
        BeanUtils.copyProperties(userDTO, existingUser, "id", "createTime");
        existingUser.setUpdateTime(LocalDateTime.now());

        return updateById(existingUser);
    }

    @Override
    public boolean deleteUser(Long userId) {
        // 删除用户
        return removeById(userId);
    }
}
